#fontworks字体动漫使用事例
import requests
from bs4 import BeautifulSoup
import bs4
import pandas as pd
import os
def getHtmlText(url):
    global header
    header = {"user-agent": "Mozilla/5.0 (windows NT 10.0; Minb4; x64) "}
    r= requests.get(url,headers=header)
##    print("状态码为:",r.status_code)
    return r.text
def bs4Analysis(html,FrontList):
    soup=BeautifulSoup(html,'html.parser') 
    for msg in soup.find_all(name='dic',class_='c-card'):  
        if isinstance(msg,bs4.element.Tag):
            msgs=msg('a')
            FrontList.append([msgs[0]['href'],msgs[0]('img')[0]['src'],msgs[0]('p')[0].string,msgs[0]('p')[1].string])
def bs4_Detail(html_d,Detail_List):
    soup_d=BeautifulSoup(html_d,'html.parser') 
    for tr in soup_d.find('tbody').children:
    #过滤非标签类型的其他信息
        try:
            if isinstance(tr,bs4.element.Tag):
                #td标签
                td=tr('td')
                #'th'标签
                th=tr('th')
                Detail_List.append([th[0].string,td[0].string])                
        except:
            pass
    anime_detail=pd.DataFrame(Detail_List,columns=["详","情"])   
    anime_name=soup_d.find_all('h1')[-1].text
    #作品名称格式    
    anime_df=pd.DataFrame([[""," "],[anime_name,""],[" ",""]],columns=["作","品"])
    anime_all_msg=pd.concat([anime_df,anime_detail])
    return anime_all_msg
def df_Save(FrontList):
    global path
    df=pd.DataFrame()
    df=pd.DataFrame(FrontList,columns=["详细链接","封面地址","作品名称","使用字体"])
    path=os.getcwd()+'\\'
    df.to_excel(path+'FrontWorks字体.xlsx',index=False)
    return df
def PhotoSave(df):
    count=1
        #创建文件夹
    try:
            os.mkdir(os.getcwd()+"\\Frontworks动漫\\")
    except:
            print("文件夹已存在")    
    for i in range(0,len(df)):
        r= requests.get(df['封面地址'][i],headers =header )
        save_path=os.getcwd()+"\\Frontworks动漫\\"+df['作品名称'][i]+'.png'
        with open(save_path,'wb') as f:
            f.write(r.content)
            f.close()
            print("已下载{}张图片,{}".format(count,df['作品名称'][i]))
            count=count+1
def main():
    #初始化变量
    FrontList=[]
    df_all=pd.DataFrame()
    #==========爬取主页信息========
    #构建网页界面
    print("正在执行")
    for i in range(1,5):
        if i ==1:
            url='https://fontworks.co.jp/case/anime/'
        else:
            url='https://fontworks.co.jp/case/anime/page/{}/'.format(i)
        html=getHtmlText(url)
        bs4Analysis(html,FrontList)
        df=df_Save(FrontList)
        #==========爬取详情信息========
    for links in df['详细链接']:
        #每次循环初始化变量
        Detail_List=[]
        html_d=getHtmlText(links)
        #只包含动漫名称的df
        anime_all=bs4_Detail(html_d,Detail_List)
        df_all=pd.concat([df_all,anime_all])
    df_all.to_excel(path+'作品详情.xlsx',index=False)
    PhotoSave(df)
    print("完成")
main()
